var comPageNum = 1;
getSpecialTypeId();

function getSpecialTypeId() {
    $.ajax({
        url: root.goodsInter.goods_getSpecialSkuTypes,
        cache: false, //禁用缓存
        type: "POST",
        success: function (data) {
            if (data.errorCode == 0) {
                var specialSkuTypesHtml = '<option value="" selected>不限</option><option value="-1">正常商品</option>';
                for (var i = 0; i < data.data.length; i++) {
                    specialSkuTypesHtml += '<option value="' + data.data[i].id + '">' + data.data[i].name + '</option>';
                }
                $(".specialTypeId").html(specialSkuTypesHtml);
            }
        }
    });
}
var dataSource = new Array();
//table的数据源
var table; //table对象
dataSource = [];

function goodsList(data) {
	if(dataSource.length>0){
	dataSource.splice(0, dataSource.length); //清空数组
    }
if(data.data.list!=null){
	$.each(data.data.list, function(i, field) {
		var rowData = new Array();
		rowData.push(field.spu_code);
        rowData.push(field.img_url == null ? "" : field.img_url);
		rowData.push(field.name);
        rowData.push(field.subtitile == null ? "" : field.subtitile)
        rowData.push(field.brand_name);
        rowData.push(field.skuPutOnNumber);
		rowData.push(field.spu_id);
		rowData.push(field.yc_sale_status);

        var date = new Date(field.creation_date);
        Y = date.getFullYear() + '-';
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
        h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
        m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()): date.getMinutes())+ ':';
        s = date.getSeconds()< 10 ? '0'+(date.getSeconds()) : date.getSeconds();

        rowData.push(Y+M+D+h+m+s);
		rowData.push(field.spu_id);
        rowData.push(field.saleAreaId);
		/*rowData.push(field.pro_useable);*/
        dataSource.push(rowData);
	});
}

	initDataTable(dataSource);

	function initDataTable(dataSource) {
		var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
		dttable.fnClearTable(); //清空一下table
		dttable.fnDestroy(); //还原初始化了的datatable
		$("#datatable").DataTable({
			"autoWidth": false,
			"ordering": true,
			"searching": false,
			"paging": false,
			"retrieve": true,
			"destroy": true,
			"bAutoWidth": true,
			"bLengthChange": true,
			"aLengthMenu": [50, 25, 10, 5],
			"oLanguage": {
				"sLengthMenu": "每页显示 _MENU_ 条记录",
				"sZeroRecords": "抱歉， 没有找到",
				"sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
				"sInfoEmpty": "没有数据",
				"sInfoFiltered": "(从 _MAX_ 条数据中检索)",
				"oPaginate": {
					"sFirst": "首页",
					"sPrevious": "前一页",
					"sNext": "后一页",
					"sLast": "尾页"
				},
				"sZeroRecords": "没有检索到数据",
				"sProcessing": "<img src='./loading.gif' />"
			},
			data: dataSource,
			columnDefs: [{
					"visible": true,
					"targets": 0
				},
				{
					"render": function(data, type, row, meta) {
                        var val = '<span><td><input class="spuId" type="checkbox" name="spuId" value = "' + row[6] + '">' + row[0] + '</td></span>';
						return val;
					},
					"targets": 0
				},
				{
					"render": function(data, type, row, meta) {
						if(row[1] != '') {
							var val = '<span id="spuImg1" ><img onclick="picShow(\'查看图片\',\'picShow.html\',\''+row[1]+'\')" src="'+row[1]+'" width="80" height="40"></span>';
							return val;
						}else {
							var val = '<span></span>';
							return val;
						}
					},
					"targets": 1
				},
				{
					"render": function(data, type, row, meta) {
						if(row[2] != '') {
							var val = '<span>' + row[2] + '</span>';
							return val;
						}else {
							var val = '<span></span>';
							return val;
						}
					},
					"targets": 2
				},

				{
					"render": function(data, type, row, meta) {
						var val = '<span class="shun_text2" style="cursor:pointer;"  title="'+ row[3] +'">'+ row[3] +'</span>';
						return val;
					},
					"targets": 3
				},
				{
					"render": function(data, type, row, meta) {
						if(row[4] != '') {
							var val = '<span>' + row[4] + '</span>';
							return val;
						}else {
							var val = '<span></span>';
							return val;
						}
					},
					"targets": 4
				},
				{
					"render": function(data, type, row, meta) {
						if(row[5] != '') {
							var val = '<span>' + row[5] + '</span>';
							return val;
						}else {
							var val = '<span></span>';
							return val;
						}
					},
					"targets": 5
				},
				{
					"render": function(data, type, row, meta) {
                        if(row[7] == 0) {
                            var val = '<span class="dropDown"> <a class="dropDown_A powerButton 425" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">未上架<i class="Hui-iconfont">&#xe6df;</i></a><ul class="dropDown-menu menu radius box-shadow powerButton 425"><li onclick="goods_start(\'\',\'' + row[6] + '\')"><a href="#">上架</a></li></ul></span>';
                            return val;
                        } else if(row[7] == 1) {
                            var val = '<span class="dropDown"> <a class="dropDown_A powerButton 425" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">已上架<i class="Hui-iconfont">&#xe6df;</i></a><ul class="dropDown-menu menu radius box-shadow powerButton 425"><li onclick="goods_end(\'\',\'' + row[6] + '\')"><a href="#">下架</a></li></ul></span>';
                            return val;
                        } else if(row[7] == 2) {
                            var val = '<span class="dropDown"> <a class="dropDown_A powerButton 425" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">已下架<i class="Hui-iconfont">&#xe6df;</i></a><ul class="dropDown-menu menu radius box-shadow powerButton 425"><li onclick="goods_start(\'\',\'' + row[6] + '\')"><a href="#">上架</a></li></ul></span>';
                            return val;
                        }
					},
                    "targets": 6
				},
                {
                    "render": function(data, type, row, meta) {
                        if(row[8] != '') {
                            var val = '<span>' + row[8] + '</span>';
                            return val;
                        }else {
                            var val = '<span></span>';
                            return val;
                        }
                    },
                    "targets": 7
                },
				{
					"render": function(data, type, row, meta) {
                        var val = '<a><span class="list powerButton 430" onclick="spu_edit(\'spu详情\',\'spu-info.html\',\'' + row[6] + '\')">查看详情</span><br/><span class="list powerButton 422" onclick="goods_check(\'sku列表\',\'goods-sku-shelf.html\',\'' + row[9] + '\', \'' + row[0] +'\', \''+ row[2] + '\')">查看下级</span></a>';
                        return val;
                    },
                    "targets": 8
				},

			],
			"fnInitComplete": function(oSettings, json) {
				setBtnDis(0, $("#productManage"));
				$("#datatable").on("change", '.spuId', function() {
					var num = $(".shun").find("input[type=checkbox]:checked").length;
					setBtnDis(num, $("#productManage"));
				});
			}
		});
		power();
	};
}

/*表单验证特殊字符*/
function ValidateValue(textbox) {
	var IllegalString = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘’";
	var textboxvalue = textbox.value;
	var index = textboxvalue.length - 1;
	var s = textbox.value.charAt(index);
	if(IllegalString.indexOf(s) >= 0) {
		s = textboxvalue.substring(0, index);
		textbox.value = s;
		layer.msg("不能输入特殊字符");
	}
}

function goods_listCategory(categoryLevel) {
	console.log($("#class1").val())
	var categoryName = $("#class1").val();
	var user_data = {
		categoryLevel: categoryLevel,
		categoryName: $("#class1").val(),
	}
	var succCallBack = function(data, status, response) {
		console.log(data)
		if(data.errorCode == "0") {
			if(data.data == null) {
				classStr = "<li>无数据</li>"
				$("#classUl1").html(classStr);
			} else {
				var classStr = "";
				for(var i = 0; i < data.data.length; i++) {
					classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
				}
				$("#classUl1").html(classStr);
			}
		}
	}
	web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

//获取光标
$("#class1").focus(function() {
	$("#classUl1").show();
	goods_listCategory(1);
});
$(document).bind("click", function(e) {
	//id为menu的是菜单，id为open的是打开菜单的按钮
	if($(e.target).closest("#classUl1").length == 0 && $(e.target).closest("#class1").length == 0) {
		//点击id为menu之外且id不是不是open，则触发
		$("#classUl1").hide()
		$("#class2").val();
	}
});
var goodslist_cantegory_id; //定义分类搜索条件
var firstCategoryId;
var secondCategoryId;
var thirdCategoryId;
var categoryIds;

// 2,3,4级的模糊查询
function getNext_input(level, category_id) {
	if(level == 4) {
		goodslist_cantegory_id = category_id;
        thirdCategoryId = category_id;
	}else if(level == 5) {
		categoryIds = category_id;
	}
	if(level < 4) {
		$("#class" + level + "")[0].oninput = function() {
			var user_data = {
				parentCateId: category_id,
				categoryName: $("#class" + level + "").val()
			}
			var succCallBack = function(data, status, response) {
				if(data.errorCode == 0) {
					if(data.data == null) {
						classStr = "<li>无数据</li>";
					} else {
						var classStr = "";
						for(var i = 0; i < data.data.length; i++) {
							classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
						}
					}
					if(data.data[0] == undefined) {
						classValue = category_id;
						var nextLevel = level + 1;
						$("#classUl" + nextLevel + "").html(classStr);
						$("#classUl" + level + "").hide();
					} else {
						var nextLevel = data.data[0].category_level;
						$("#classUl" + nextLevel + "").html(classStr);
						$("#classUl" + level + "").show();
					}
				}
			}
			web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
		}
		//获取光标
		$("#class" + level + "").focus(function() {
			$("#classUl" + level + "").show();
		});
		$(document).bind("click", function(e) {
			//id为menu的是菜单，id为open的是打开菜单的按钮
			if($(e.target).closest("#classUl" + level + "").length == 0 && $(e.target).closest("#class" + level + "").length == 0) {
				//点击id为menu之外且id不是不是open，则触发
				$("#classUl" + level + "").hide()
			}
		});
	}
}
function nextClass(category_id, level, category_name) {
	console.log(level)
	$("#class" + level + "").val(category_name);
	if(level == 1) {
        firstCategoryId = category_id;
		$("#class2").val("");
		$("#class3").val("");
		$("#class4").val("");
	} else if(level == 2) {
        secondCategoryId = category_id;
		$("#class3").val("");
		$("#class4").val("");
	}else if(level == 3) {
		$("#class4").val("");
	}
	var user_data = {
		parentCateId: category_id,
	}
	var succCallBack = function(data, status, response) {
		if(data.errorCode == "0") {
			if(data.data == null) {
				classStr = "<li>无数据</li>";
			} else {
				var classStr = "";
				for(var i = 0; i < data.data.length; i++) {
					classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
				}
			}
			if(data.data[0] == undefined) {
				classValue = category_id;
				var nextLevel = level + 1;
				$("#classUl" + nextLevel + "").html(classStr);
				$("#classUl" + level + "").hide();
			} else {
				var nextLevel = data.data[0].category_level;
				$("#classUl" + nextLevel + "").html(classStr);
				$("#classUl" + nextLevel + "").show();
				$("#classUl" + level + "").hide()
			}
		}
	}
	getNext_input(level + 1, category_id);
	web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}
/*查看*/
function goods_check(title, url, spuId, spuCode, spuName) {
	sessionStorage.removeItem("skuImgCache");
	sessionStorage.setItem("spuId", spuId);
	sessionStorage.setItem("spuCode", spuCode);
	sessionStorage.setItem("spuName", spuName);
    sessionStorage.setItem("areaId", $("#areaId").html());
	sessionStorage.setItem("saleArea", $("#areaId").html());

	var index = layer.open({
		type: 2,
		title: title,
		content: url
	});
	layer.full(index);
}

/*账户信息编辑*/
function spu_edit(title, url, row) {
	/*删除添加spu图片的缓存，防止刷新页面后缓存不消失*/
	sessionStorage.removeItem("spuImgCache");
	sessionStorage.removeItem("brand_name");
	sessionStorage.removeItem("brand_id");
	sessionStorage.removeItem("attrObjCanch");
	sessionStorage.removeItem("attrId");
	window.session_storage.setItem('spu_id', row)
	var index = layer.open({
		type: 2,
		title: title,
		content: url
	});
	layer.full(index);
}

function reloadSpuTable(pageNum) {
	comPageNum = pageNum;
  /*  var customerType = $("input:checkbox[name='customerType']:checked").map(function(index,elem) {
        return $(elem).val();
    }).get().join(',');

    if(customerType.indexOf("1")>-1 && customerType.indexOf("2")>-1){
        customerType = 3;
    }*/
  /*  var saleMsg = $("input:checkbox[name='saleArea']:checked").map(function(index,elem) {
        return $(elem).val();
    }).get().join(',');
    if(saleMsg == "" || saleMsg == undefined || saleMsg == null ){
        saleMsg = -1;
	}*/


    var firstCategoryName = $("#class1").val();
    var secondCategoryName = $("#class2").val();
	var thirdCategoryName = $("#class3").val();
	var categoryIdName = $("#class4").val();
    if(thirdCategoryName == "" || thirdCategoryName == undefined || thirdCategoryName == null){
        goodslist_cantegory_id = null;
        thirdCategoryId= null;
    }

    if(firstCategoryName == "" || firstCategoryName == undefined || firstCategoryName == null){
        firstCategoryId = null;
    }

    if(secondCategoryName == "" || secondCategoryName == undefined || secondCategoryName == null){
        secondCategoryId = null;
    }
	if(categoryIdName == "" || categoryIdName == undefined || categoryIdName == null){
		categoryIds = null;
	}

	$.ajax({
		contentType: 'application/json',
		url: root.goodsInter.goods_spuListWithShelfStatus,
		cache: false, //禁用缓存
		type: "POST",
		data: JSON.stringify({
			pageSize: 50,
			nowPage: pageNum,
			model: {
                firstCategoryId : firstCategoryId,
                secondCategoryId :secondCategoryId,
				thirdCategoryId:goodslist_cantegory_id,
				categoryId:categoryIds,
				spuCode: $("#spu_code").val(),
				skuCode:$("#Code").val(),
                subtitleName:$("#subtilte").val(),
                creationDateBegin:$("#creationDateBegin").val(),
                creationDateEnd:$("#creationDateEnd").val(),
				nameParam: $("#goodsName").val(),
				brandParam: $("#brandName").val(),
				saleStatus: $("#saleStatus").val(),
			} //传入组装的参数
		}),
		success: function(data) {
			/*if(data.data.list.length==0&&comPageNum!=1){
				reloadSpuTable(comPageNum-1);
				return;
			}*/
			goodsList(data);
			$("#spu_all").attr("checked", false);
			totalPage = data.data.totalPage;
			$('.M-box3').pagination({
				pageCount: totalPage,
				current: comPageNum,
				jump: true,
				coping: true,
				prevContent: '上页',
				nextContent: '下页',
				callback: function(api) {
					comPageNum = api.getCurrent();
					reloadSpuTable(api.getCurrent());
				}
			});
		}
	});
}
//获取用户信息
var localStorageParameters = decodeURIComponent(web.readCookie("loginData"));
var JsonObject =JSON.parse(localStorageParameters);
//上架
function goods_start(obj, id) {
    console.log(id);
	/*var spu_data1 = {
		id: id,
	}
	var succCallBack1 = function(data, status, response) {
		if(data.errorCode != 0) {
			$.Huimodalalert(data.errorMessage, 2000);
		}else{
			console.log(id);

		}
	};
	return web.doAjax(root.goodsInter.goods_singleSpuIsPull, 'post', spu_data1, succCallBack1);*/
	layer.confirm('确认要上架吗？', function(index) {
		var spu_data = {
			ids: id,
			status: 1,
			lastModifiedBy:JsonObject.user.user_ID,
			lastModifiedName:JsonObject.user.name,
			operateSource:15//云采上架
		}
		var succCallBack = function(data, status, response) {
			var errmsg = data.errorMessage?data.errorMessage:"" ;
			if(data.errorCode == 0) {
				layer.msg("上架成功有"+data.allowOperateSkus.length+"个商品,上架失败有"+data.notAllowOperateSkus.length +"个商品!", {
					icon: 6,
					time: 1000
				}, function() {
					reloadSpuTable(comPageNum);
				});
			}else{
				layer.msg("上架失败:"+data.errorMessage, {
					icon: 6,
					time: 1000
				}, function() {
					reloadSpuTable(comPageNum);
				});
			}
		};
		return web.doAjax(root.goodsInter.goods_setSpuSaleStatus, 'post', spu_data, succCallBack);
	});
}

//下架
function goods_end(obj, id) {
	console.log(id);
	layer.confirm('确认要下架吗？', function(index) {
		var spu_data = {
			ids: id,
			status: 2,
            lastModifiedBy:JsonObject.user.user_ID,
			lastModifiedName:JsonObject.user.name,
			operateSource:25//云采下架
		}
		var succCallBack = function(data, status, response) {
			if(data.errorCode == 0) {
				layer.msg("下架成功有"+data.allowOperateSkus.length+"个商品,下架失败有"+data.notAllowOperateSkus.length +"个商品!", {
					icon: 6,
					time: 1000
				}, function() {
					reloadSpuTable(comPageNum);
				});
			}else{
				layer.msg("下架失败:"+data.errorMessage, {
					icon: 6,
					time: 1000
				}, function() {
					reloadSpuTable(comPageNum);
				});
			}
		};
		return web.doAjax(root.goodsInter.goods_setSpuSaleStatus, 'post', spu_data, succCallBack);
	});
}
var allIds = ""; //批量上下架的id
function stopProp() {
	/*批量上架全选框阻止冒泡*/
	var timer = setTimeout(function() {
		var num = $("#datatable").find("tbody").find("input[type=checkbox]:checked").length;
		setBtnDis(num, $("#productManage"));
		clearTimeout(timer);
	}, 200)

	window.event ? window.event.cancelBubble = true : e.stopPropagation();
}

//批量上架
function goods_up(obj) {
	layer.confirm('确认要批量上架吗？', function(index) {
		allIds = document.getElementsByClassName('spuId');
		var ids = [];
		for(var i = 0; i < allIds.length; i++) {
			if(allIds[i].checked == true) {
				ids.push(allIds[i]);
			}
		}
		var idStr = "";
		for(var i = 0; i < ids.length; i++) {
			idStr += ids[i].value + ","
		}
		idStr = idStr.substring(0, idStr.length - 1);
		var spu_data = {
			ids: idStr,
			status: 1,
            lastModifiedBy:JsonObject.user.user_ID,
			lastModifiedName:JsonObject.user.name,
			operateSource:15//云采上架
		}
		var succCallBack = function(data, status, response) {
            var errmsg = data.errorMessage?data.errorMessage:"" ;
			if(data.errorCode == 0) {
				layer.msg("上架成功有"+data.allowOperateSkus.length+"个商品,上架失败有"+data.notAllowOperateSkus.length +"个商品!", {
					icon: 6,
					time: 1000
				}, function() {
					reloadSpuTable(comPageNum);
				});
			}else{
                layer.msg("上架失败:"+data.errorMessage, {
                    icon: 6,
                    time: 1000
                }, function() {
                    reloadSpuTable(comPageNum);
                });
			}
		};
		return web.doAjax(root.goodsInter.goods_setSpuSaleStatus, 'post', spu_data, succCallBack);
	});
}

//批量下架
function goods_down(obj) {
	layer.confirm('确认要批量下架吗？', function(index) {
		allIds = document.getElementsByClassName('spuId');
		var ids = [];
		for(var i = 0; i < allIds.length; i++) {
			console.log(allIds[i].checked)
			if(allIds[i].checked == true) {
				ids.push(allIds[i]);
			}
		}
		var idStr = "";
		for(var i = 0; i < ids.length; i++) {
			idStr += ids[i].value + ","
		}
		idStr = idStr.substring(0, idStr.length - 1);
		var spu_data = {
			ids: idStr,
			status: 2,
            lastModifiedBy:JsonObject.user.user_ID,
			lastModifiedName:JsonObject.user.name,
			operateSource:25//云采下架
		}
		var succCallBack = function(data, status, response) {

			if(data.errorCode == 0) {
				layer.msg("下架成功有"+data.allowOperateSkus.length+"个商品,下架失败有"+data.notAllowOperateSkus.length +"个商品!", {
					icon: 6,
					time: 1000
				}, function() {
					reloadSpuTable(comPageNum);
				});
			}else{
				layer.msg("下架失败:"+data.errorMessage, {
					icon: 6,
					time: 1000
				}, function() {
					reloadSpuTable(comPageNum);
				});
			}
		};
		return web.doAjax(root.goodsInter.goods_setSpuSaleStatus, 'post', spu_data, succCallBack);
	});
}

/*商品图片管理-----------------------------------------------------------------------------------*/
function imgGoods_listCategory(categoryLevel) {
	var categoryName = $("#imgClass1").val();
	var user_data = {
		categoryLevel: categoryLevel,
		categoryName: $("#imgClass1").val(),
	}
	var succCallBack = function(data, status, response) {
		console.log(data)
		if(data.errorCode == "0") {
			if(data.data == null) {
				classStr = "<li>无数据</li>"
				$("#img-classUl1").html(classStr);
			} else {
				var classStr = "";
				for(var i = 0; i < data.data.length; i++) {
					classStr += "<li onclick='imgNextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
				}
				$("#img-classUl1").html(classStr);
			}
		}
	}
	web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

//获取光标
$("#imgClass1").focus(function() {
	$("#img-classUl1").show();
	imgGoods_listCategory(1);
});
$(document).bind("click", function(e) {
	//id为menu的是菜单，id为open的是打开菜单的按钮
	if($(e.target).closest("#img-classUl1").length == 0 && $(e.target).closest("#imgClass1").length == 0) {
		//点击id为menu之外且id不是不是open，则触发
		$("#img-classUl1").hide()
	}
});
var oneCategoryId = "";
var twoCategoryId = "";
var threeCategoryId = "";
// 2,3,4级的模糊查询
function imgGetNext_input(level, category_id) {
	if(level < 4) {
		$("#imgClass" + level + "")[0].oninput = function() {
			console.log(level)
			console.log($("#imgClass" + level + "").val())
			if(level == 1) {
				oneCategoryId = category_id;
			} else if(level == 2) {
				twoCategoryId = category_id;
			} else if(level == 3) {
				threeCategoryId = category_id;
			}
			var user_data = {
				parentCateId: category_id,
				categoryName: $("#imgClass" + level + "").val()
			}
			var succCallBack = function(data, status, response) {
				console.log(data)
				if(data.errorCode == "0") {
					if(data.data == null) {
						classStr = "<li>无数据</li>";
					} else {
						var classStr = "";
						for(var i = 0; i < data.data.length; i++) {
							classStr += "<li onclick='imgNextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
						}
					}
					if(data.data[0] == undefined) {
						classValue = category_id;
						var nextLevel = level + 1;
						$("#img-classUl" + nextLevel + "").html(classStr);
						$("#img-classUl" + level + "").hide();
					} else {
						var nextLevel = data.data[0].category_level;
						$("#img-classUl" + nextLevel + "").html(classStr);
						$("#img-classUl" + level + "").show();
					}
				}
			}
			web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
		}
		//获取光标
		$("#imgClass" + level + "").focus(function() {
			$("#img-classUl" + level + "").show();
		});
		$(document).bind("click", function(e) {
			//id为menu的是菜单，id为open的是打开菜单的按钮
			if($(e.target).closest("#img-classUl" + level + "").length == 0 && $(e.target).closest("#imgClass" + level + "").length == 0) {
				//点击id为menu之外且id不是不是open，则触发
				$("#img-classUl" + level + "").hide()
			}
		});
	}

}

function imgNextClass(category_id, level, category_name) {
	console.log(level)
	console.log(category_id)
	if(level == 1) {
		$("#imgClass2").val("");
		$("#imgClass3").val("");
	} else if(level == 2) {
		$("#imgClass3").val("");
	}
	if(level == 1) {
		oneCategoryId = category_id;
	} else if(level == 2) {
		twoCategoryId = category_id;
	} else if(level == 3) {
		threeCategoryId = category_id;
	}
	$("#imgClass" + level + "").val(category_name)
	var user_data = {
		parentCateId: category_id
	}
	var succCallBack = function(data, status, response) {
		console.log(data)
		if(data.errorCode == "0") {
			if(data.data == null) {
				classStr = "<li>无数据</li>";
			} else {
				var classStr = "";
				for(var i = 0; i < data.data.length; i++) {
					classStr += "<li onclick='imgNextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
				}
			}
			if(data.data[0] == undefined) {
				classValue = category_id;
				var nextLevel = level + 1;
				$("#img-classUl" + nextLevel + "").html(classStr);
				$("#img-classUl" + level + "").hide();
			} else {
				var nextLevel = data.data[0].category_level;
				$("#img-classUl" + nextLevel + "").html(classStr);
				$("#img-classUl" + nextLevel + "").show();
				$("#img-classUl" + level + "").hide()
			}
		}
	}
	imgGetNext_input(level + 1, category_id);
	web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}
var totalPage = 1;

function img_list() {
	console.log(JSON.stringify({
        "pageSize": "50",
        "nowPage": 1,
        "model": {
            "spuCode": $("#spuCode").val(),
            "skuCode": $("#skuCode").val(),
            "imgName": $("#imgName").val(),
            "oneCategoryId": oneCategoryId,
            "twoCategoryId": twoCategoryId,
            "threeCategoryId": threeCategoryId
        }
    }))

	$.ajax({
		contentType: "application/json",
		type: "POST",
		url: root.goodsInter.goods_listImg,
		cache: false, //禁用缓存
		dataType: "json",
		data: JSON.stringify({
			"pageSize": "50",
			"nowPage": 1,
			"model": {
				"spuCode": $("#spuCode").val(),
				"skuCode": $("#skuCode").val(),
				"imgName": $("#imgName").val(),
				"oneCategoryId": oneCategoryId,
				"twoCategoryId": twoCategoryId,
				"threeCategoryId": threeCategoryId
			}
		}),
		success: function(data) {
			if(data.errorCode == 0) {
				var imgHtmlStr = "";
                var objList = data.data.list;
				if(objList != null) {
					for(var i = 0; i < objList.length; i++) {
						if (objList[i].img_name == null || objList[i].img_name == "null") {
                            objList[i].img_name = "";
						}
						if (objList[i].img_url != null && objList[i].img_url != "null") {
                            if (objList[i].use_img == 0) {
                                imgHtmlStr += '<li><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + objList[i].img_url + '\',\'500\',\'300\',\'110\')" src="' + objList[i].img_url + '"><div class="num">编码： <span>' + objList[i].img_id + '</span></div><div class="name">名称： <span>' + objList[i].img_name + '</span></div><div class="sale_pic_btn"><a onclick="updataImg(' + objList[i].img_id + ')">修改</a><a onclick="deleteImg(' + objList[i].img_id + ')">删除</a></div></li>';
                            } else if (objList[i].use_img == 1) {
                                imgHtmlStr += '<li><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + objList[i].img_url + '\',\'500\',\'300\',\'110\')" src="' + objList[i].img_url + '"><div class="num">编码： <span>' + objList[i].img_id + '</span></div><div class="name">名称： <span>' + objList[i].img_name + '</span></div><div class="sale_pic_btn"></div></li>';
                            }
						}

					}
					$("#imgListBox").html(imgHtmlStr);
				}
				totalPage = data.data.totalPage
				$('.M-box4').pagination({
					pageCount: totalPage,
					jump: true,
					coping: true,
					prevContent: '上页',
					nextContent: '下页',
					callback: function(api) {
						console.log(api.getCurrent());
						$.ajax({
							contentType: "application/json",
							type: "POST",
                            url: root.goodsInter.goods_listImg,
							cache: false, //禁用缓存
							dataType: "json",
							data: JSON.stringify({
								"pageSize": "50",
								"nowPage": api.getCurrent(),
								"model": {
									"spuCode": $("#spuCode").val(),
									"skuCode": $("#skuCode").val(),
									"imgName": $("#imgName").val(),
									"oneCategoryId": oneCategoryId,
									"twoCategoryId": twoCategoryId,
									"threeCategoryId": threeCategoryId
								}
							}),
							success: function(data) {
								console.log(data);
								if(data.errorCode == 0) {
									var imgHtmlStr = "";
                                    var objList = data.data.list;
									if(objList != null) {
										for(var i = 0; i < objList.length; i++) {
                                            if (objList[i].img_name == null || objList[i].img_name == "null") {
                                                objList[i].img_name = "";
                                            }
                                            if (objList[i].img_url != null && objList[i].img_url != "null") {
                                                if (objList[i].use_img == 0) {
                                                    imgHtmlStr += '<li><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + objList[i].img_url + '\',\'500\',\'300\',\'110\')" src="' + objList[i].img_url + '"><div class="num">编码： <span>' + objList[i].img_id + '</span></div><div class="name">名称： <span>' + objList[i].img_name + '</span></div><div class="sale_pic_btn"><a onclick="updataImg(' + objList[i].img_id + ')">修改</a><a onclick="deleteImg(' + objList[i].img_id + ')">删除</a></div></li>';
                                                } else if (objList[i].use_img == 1) {
                                                    imgHtmlStr += '<li><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + objList[i].img_url + '\',\'500\',\'300\',\'110\')" src="' + objList[i].img_url + '"><div class="num">编码： <span>' + objList[i].img_id + '</span></div><div class="name">名称： <span>' + objList[i].img_name + '</span></div><div class="sale_pic_btn"></div></li>';
                                                }
                                            }

										}
										$("#imgListBox").html(imgHtmlStr);
									}
									totalPage = data.data.totalPage
								}
							},
							error: function(XMLHttpRequest, textStatus, errorThrown) {
								alert(XMLHttpRequest);
							}
						});
					}
				});
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert(XMLHttpRequest);
		}
	});
}

function picShow(title, url, imgUrl) {
	window.event ? window.event.cancelBubble = true : e.stopPropagation();
	sessionStorage.setItem("imgUrl", imgUrl);
	layer_show(title, url, "800", "500");
}

function addImg() {
	layer_show("增加图片", "addPic.html", "600", "500");
}

function updataImg(imgId) {
	$.ajax({
		contentType: "application/json",
		type: "POST",
		url: root.goodsInter.goods_getImg,
		cache: false, //禁用缓存
		dataType: "json",
		data: JSON.stringify({
			"imgId": imgId
		}),
		success: function(data) {
			console.log(data);
			if(data.errorCode == 0) {
				// 未使用，随便修
				sessionStorage.setItem("imgInfo", JSON.stringify(data));
				layer_show("修改图片", "can-updataImg.html", "600", "400");

				/*if(data.use_img == 0) {
				} else if(data.use_img == 1) {
					//已使用，只能修改名字
					sessionStorage.setItem("imgInfo", JSON.stringify(data));
					layer_show("修改图片", "cannot-updataImg.html", "600", "400");
				}*/
			}

		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert(XMLHttpRequest);
		}
	});
}

function deleteImg(imgId) {
	layer.confirm('确认要删除吗？', function(index) {
		$.ajax({
			contentType: "application/json",
			type: "POST",
			url: root.goodsInter.goods_delImg,
			cache: false, //禁用缓存
			dataType: "json",
			data: JSON.stringify({
				"imgId": imgId
			}),
			success: function(data) {
				console.log(data);
				if(data.errorCode == 0) {
					var index = parent.layer.getFrameIndex(window.name);
					parent.layer.close(index);
					layer.msg("删除成功", {
						icon: 6,
						time: 1000
					}, function() {
						img_list();
					});
				} else {
					layer.msg(data.errorMessage, {
						icon: 5,
						time: 1000
					}, function() {
						var index = parent.layer.getFrameIndex(window.name);
						parent.layer.close(index);
					});
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert(XMLHttpRequest);
			}
		});
	});
}

function setBtnDis(num, pnode) { //如果选中项为空时，置灰相关按钮
	if(num <= 0) {
		pnode.find(".goods_edit").attr("disabled", "disabled").addClass("dis_btn");
	} else {
		pnode.find(".goods_edit").removeAttr("disabled").removeClass("dis_btn");
	}
}